'use client';

import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Space, Modal, Form, message, Popconfirm, Select, Row, Col, Tag, Tooltip, Upload } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined, PlusOutlined, FilterOutlined, ReloadOutlined, UploadOutlined, EyeOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { 
  getAllArticles, 
  getAllArticlesWithToken,
  getArticlesByType, 
  createArticle, 
  updateArticle, 
  deleteArticle, 
  restoreArticle,
  hardDeleteArticle, 
  ArticleType, 
  Article, 
  Attachment 
} from '@/lib/articles';
import Layout from '@/components/Layout';
import moment from 'moment';

const { TextArea } = Input;
const { Option } = Select;
const { confirm } = Modal;

// 文章类型选项
const ARTICLE_TYPE_OPTIONS = [
  { value: ArticleType.DEPARTMENT_INTRO, label: '部门介绍' },
  { value: ArticleType.ETHICS, label: '师德师风' },
  { value: ArticleType.DEVELOPMENT, label: '教师发展' },
  { value: ArticleType.ETHICS_REPORT, label: '师德师风举报' },
  { value: ArticleType.TITLE_REVIEW, label: '职称评审' },
  { value: ArticleType.DOWNLOADS, label: '资料下载' },
  { value: ArticleType.PROCESS, label: '办事流程' }
];

// 文章状态选项
const ARTICLE_STATUS_OPTIONS = [
  { value: false, label: '禁用', color: 'error' },
  { value: true, label: '启用', color: 'success' }
];

// 定义表单值类型
interface ArticleFormValues {
  title: string;
  content: string;
  articleType: ArticleType;
  hasAttachment: boolean;
  attachments?: any[];
  status?: number;
}

const ArticleManagementPage = () => {
  const [articles, setArticles] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm<ArticleFormValues>();
  const [editingArticle, setEditingArticle] = useState<any | null>(null);
  const [searchText, setSearchText] = useState('');
  
  // 添加查询条件状态
  const [queryArticleType, setQueryArticleType] = useState<ArticleType | undefined>(undefined);
  const [queryStatus, setQueryStatus] = useState<boolean | undefined>(undefined);

  useEffect(() => {
    fetchArticles();
  }, []);

  const fetchArticles = async () => {
    setLoading(true);
    try {
      let response;
      
      // 根据查询条件获取文章
      if (queryArticleType !== undefined) {
        response = await getArticlesByType(queryArticleType);
      } else {
        response = await getAllArticlesWithToken();
      }
      
      console.log('【查询文章】响应结果:', response.data);
      
      if (response.data.code === 1) {
        let articleData = response.data.data || [];
        
        // 如果有状态筛选，在前端进行过滤
        // 注意：这里只是筛选显示，不影响数据库中的文章
        if (queryStatus !== undefined) {
          // 使用双等号比较，允许布尔值和数字之间的比较
          articleData = articleData.filter(article => article.status == queryStatus);
        }
        
        setArticles(articleData);
        if (articleData.length === 0) {
          message.info('暂无文章数据');
        }
      } else {
        throw new Error(response.data.msg || '获取文章失败');
      }
    } catch (error: any) {
      console.error('获取文章列表失败:', error);
      message.error('获取文章列表失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 重置查询条件
  const handleResetQuery = () => {
    setQueryArticleType(undefined);
    setQueryStatus(undefined);
    setSearchText('');
    // 重置后重新查询
    setTimeout(() => {
      fetchArticles();
    }, 0);
  };

  // 执行查询
  const handleQuery = () => {
    fetchArticles();
  };

  const showModal = (record: any | null = null) => {
    setEditingArticle(record);
    if (record) {
      form.setFieldsValue({
        title: record.title,
        content: record.content,
        articleType: record.articleType,
        hasAttachment: record.hasAttachment,
        // 附件需要特殊处理
        attachments: record.attachments || [],
        status: record.status
      });
    } else {
      form.resetFields();
      // 设置默认值
      form.setFieldsValue({
        hasAttachment: false,
        status: 1
      });
    }
    setModalVisible(true);
  };

  const handleModalOk = () => {
    form.validateFields().then(values => {
      if (editingArticle) {
        handleEditArticle(values);
      } else {
        handleAddArticle(values);
      }
    });
  };

  const handleAddArticle = async (values: ArticleFormValues) => {
    try {
      const articleData = {
        ...values,
        status: 1, // 默认为启用状态
        publishDate: moment().format('YYYY-MM-DDTHH:mm:ss'),
        author: '当前用户', // 实际应用中应该从用户会话中获取
        editor: '当前用户',
        viewCount: 0
      };
      
      console.log('【添加文章】请求参数:', articleData);
      const response = await createArticle(articleData);
      console.log('【添加文章】响应结果:', response.data);
      
      if (response.data.code === 1) {
        message.success('添加文章成功');
        setModalVisible(false);
        fetchArticles();
      } else {
        throw new Error(response.data.msg || '添加失败');
      }
    } catch (error: any) {
      console.error('添加文章失败:', error);
      message.error('添加文章失败: ' + (error.message || '未知错误'));
    }
  };

  const handleEditArticle = async (values: ArticleFormValues) => {
    try {
      if (!editingArticle) {
        throw new Error('编辑的文章不存在');
      }
      
      const articleData = {
        ...values,
        editor: '当前用户', // 实际应用中应该从用户会话中获取
      };
      
      console.log('【更新文章】请求参数:', articleData);
      const response = await updateArticle(editingArticle.id, articleData);
      console.log('【更新文章】响应结果:', response.data);
      
      if (response.data.code === 1) {
        message.success('更新文章成功');
        setModalVisible(false);
        fetchArticles();
      } else {
        throw new Error(response.data.msg || '更新失败');
      }
    } catch (error: any) {
      console.error('更新文章失败:', error);
      message.error('更新文章失败: ' + (error.message || '未知错误'));
    }
  };

  const handleToggleStatus = (id: number, currentStatus: boolean) => {
    const action = currentStatus ? '隐藏' : '显示';
    confirm({
      title: `确定要${action}这篇文章吗?`,
      icon: <ExclamationCircleOutlined />,
      content: currentStatus 
        ? '隐藏后，文章在前台将不再显示给用户，但在管理页面仍然可见' 
        : '显示后，文章将可以在前台被用户查看',
      okText: '确定',
      okType: currentStatus ? 'danger' : 'primary',
      cancelText: '取消',
      onOk: async () => {
        try {
          console.log(`【${action}文章】请求参数:`, { id });
          // 使用软删除API来修改状态
          let response;
          if(action === '显示'){
            response = await restoreArticle(id);
          }else{
            response = await deleteArticle(id);
          }
          
          console.log(`【${action}文章】响应结果:`, response.data);
          
          if (response.data.code === 1) {
            message.success(`${action}文章成功`);
            fetchArticles(); // 重新获取所有文章，包括状态已更改的文章
          } else {
            throw new Error(response.data.msg || `${action}失败`);
          }
        } catch (error: any) {
          console.error(`${action}文章失败:`, error);
          message.error(`${action}文章失败: ` + (error.message || '未知错误'));
        }
      }
    });
  };

  const handleDelete = (id: number) => {
    confirm({
      title: '确定要删除这篇文章吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后可以在回收站恢复',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          console.log('【删除文章】请求参数:', { id });
          const response = await deleteArticle(id);
          console.log('【删除文章】响应结果:', response.data);
          
          if (response.data.code === 1) {
            message.success('删除文章成功');
            fetchArticles();
          } else {
            throw new Error(response.data.msg || '删除失败');
          }
        } catch (error: any) {
          console.error('删除文章失败:', error);
          message.error('删除文章失败: ' + (error.message || '未知错误'));
        }
      }
    });
  };

  const handleHardDelete = (id: number) => {
    confirm({
      title: '确定要永久删除这篇文章吗?',
      icon: <ExclamationCircleOutlined />,
      content: '此操作不可恢复，文章将被永久删除',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          console.log('【永久删除文章】请求参数:', { id });
          const response = await hardDeleteArticle(id);
          console.log('【永久删除文章】响应结果:', response.data);
          
          if (response.data.code === 1) {
            message.success('永久删除文章成功');
            fetchArticles();
          } else {
            throw new Error(response.data.msg || '删除失败');
          }
        } catch (error: any) {
          console.error('永久删除文章失败:', error);
          message.error('永久删除文章失败: ' + (error.message || '未知错误'));
        }
      }
    });
  };

  const columns = [
    { 
      title: '标题', 
      dataIndex: 'title', 
      key: 'title',
      ellipsis: true,
      width: '20%'
    },
    { 
      title: '类型', 
      dataIndex: 'articleType', 
      key: 'articleType',
      render: (type: ArticleType) => {
        const articleType = ARTICLE_TYPE_OPTIONS.find(t => t.value === type);
        return articleType ? articleType.label : '未知类型';
      },
      width: '8%'
    },
    { 
      title: '前台显示状态', 
      dataIndex: 'status', 
      key: 'status',
      render: (status: boolean) => {
        // 根据状态值显示对应的标签
        if (status === true) {
          return <Tag color="success">前台可见</Tag>;
        } else {
          return <Tag color="error">前台隐藏</Tag>;
        }
      },
      width: '10%'
    },
    { 
      title: '作者', 
      dataIndex: 'author', 
      key: 'author',
      width: '8%'
    },
    { 
      title: '发布日期', 
      dataIndex: 'publishDate', 
      key: 'publishDate',
      render: (text: string) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
      width: '15%'
    },
    { 
      title: '浏览次数', 
      dataIndex: 'viewCount', 
      key: 'viewCount',
      width: '8%'
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button 
            icon={<EyeOutlined />} 
            onClick={() => message.info(`查看文章: ${record.title}`)}
          >
            查看
          </Button>
          <Button 
            icon={<EditOutlined />} 
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          {record.status ? (
            <Button
              danger
              onClick={() => handleToggleStatus(record.id, record.status)}
            >
              前台隐藏
            </Button>
          ) : (
            <Button
              type="primary"
              onClick={() => handleToggleStatus(record.id, record.status)}
            >
              前台显示
            </Button>
          )}
          <Popconfirm
            title="确定要永久删除这篇文章吗？"
            onConfirm={() => handleHardDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              icon={<DeleteOutlined />} 
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
      width: '35%'
    },
  ];

  const filteredArticles = articles.filter(
    article => article.title.toLowerCase().includes(searchText.toLowerCase()) ||
               article.content.toLowerCase().includes(searchText.toLowerCase())
  );

  // 查询表单组件
  const renderQueryForm = () => (
    <Card style={{ marginBottom: 16 }}>
      <Row gutter={16}>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="文章类型" style={{ marginBottom: 0 }}>
            <Select
              placeholder="选择文章类型"
              style={{ width: '100%' }}
              allowClear
              value={queryArticleType}
              onChange={(value) => setQueryArticleType(value)}
            >
              {ARTICLE_TYPE_OPTIONS.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="前台显示状态" style={{ marginBottom: 0 }}>
            <Select
              placeholder="选择状态"
              style={{ width: '100%' }}
              allowClear
              value={queryStatus}
              onChange={(value) => setQueryStatus(value)}
            >
              <Option key="true" value={true}>前台可见</Option>
              <Option key="false" value={false}>前台隐藏</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6}>
          <Form.Item label="关键字" style={{ marginBottom: 0 }}>
            <Input
              placeholder="搜索文章标题或内容"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<SearchOutlined />}
              allowClear
            />
          </Form.Item>
        </Col>
        <Col xs={24} sm={12} md={6} lg={6} style={{ textAlign: 'right', display: 'flex', alignItems: 'flex-end', justifyContent: 'flex-end' }}>
          <Button 
            type="primary" 
            icon={<FilterOutlined />} 
            onClick={handleQuery}
            style={{ marginRight: 8 }}
          >
            查询
          </Button>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={handleResetQuery}
          >
            重置
          </Button>
        </Col>
      </Row>
    </Card>
  );

  return (
    <Layout>
      <Card title="人事文章管理">
        {renderQueryForm()}
        <div style={{ marginBottom: 16, textAlign: 'right' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal(null)}>
            添加文章
          </Button>
        </div>
        <Table
          columns={columns}
          dataSource={filteredArticles}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            defaultPageSize: 10,
            pageSizeOptions: ['10', '20', '50', '100']
          }}
        />
      </Card>

      <Modal
        title={editingArticle ? "编辑文章" : "添加文章"}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={800}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="title" label="标题" rules={[{ required: true, message: '请输入标题' }]}>
            <Input />
          </Form.Item>
          <Form.Item 
            name="articleType" 
            label="文章类型" 
            rules={[{ required: true, message: '请选择文章类型' }]}
          >
            <Select placeholder="请选择文章类型">
              {ARTICLE_TYPE_OPTIONS.map(type => (
                <Option key={type.value} value={type.value}>{type.label}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="content" label="内容" rules={[{ required: true, message: '请输入内容' }]}>
            <TextArea rows={10} />
          </Form.Item>
          <Form.Item name="hasAttachment" label="是否有附件" valuePropName="checked">
            <Select>
              <Option value={true}>是</Option>
              <Option value={false}>否</Option>
            </Select>
          </Form.Item>
          <Form.Item 
            name="attachments" 
            label="附件" 
            hidden={!form.getFieldValue('hasAttachment')}
          >
            <Upload
              name="file"
              action="/api/upload" // 实际应用中应该指向真实的上传API
              listType="text"
              beforeUpload={() => {
                message.info('上传功能需要后端支持');
                return false;
              }}
            >
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default ArticleManagementPage; 